//
//  ComposeViewController.swift
//  TWeibo
//
//  Created by wtw on 15/8/6.
//  Copyright © 2015年 wtw. All rights reserved.
//

import UIKit

class ComposeViewController: UIViewController {

    //MARK: - 监听方法
    /// 关闭微博
    func close() {
        //关闭键盘，释放第一响应者
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    /// 发送微博
    func sendStatus() {
        print("发布微博")
    }
    
    //选择表情
    func inputEmoticon()  {
        print("选择表情")
    }
    
    //进入界面就激活键盘
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        //成为第一响应者
        textView.becomeFirstResponder()
    }
    //MARK: - 键盘监听方法
    override func viewDidLoad() {
        super.viewDidLoad()
        //添加监听
        addKeyboardObserver()
    }
    
    //移除监听
    deinit {
        removeKeyboardObserver()
    }
    
    /// 添加监听键盘通知
    private func addKeyboardObserver() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardDidChangeFrameNotification, object: nil)
    }
    ///移除监听通知
    private func removeKeyboardObserver() {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //键盘变化监听方法，由通知中心监听到之后，由运行循环来执行，不需要设置为private
    func keyboardChanged(n: NSNotification) {
        
        print(n)
        
        //获取目标的frame
        let rect = n.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        //动画时长
        let duration = n.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        //设置约束
        toolbarBottomCons?.constant = -(UIScreen.mainScreen().bounds.height - rect.origin.y)
        
        //动画
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    //MARK: - 搭建界面 
    //纯代码开发的时候更加倾向于用loadview()这个方法
    //苹果官方专门为纯代码创建界面而准备的函数，并且要在loadview中把整个控件都要搭建起来
    override func loadView() {
        //先实例化view
        view = UIView()
        
        //凡是视图控制器都要设置背景颜色，不然会让用户看到有点类似卡顿的情况
        //如果发现动画切换视图控制器变慢，或者闪烁，重点检查是否设置了背景颜色
        view.backgroundColor = UIColor.whiteColor()
    
        //准备导航栏
        prepareNav()
        //准备 toolbar
        prepareToolbar()
        //准备文本框
        prepareTextView()
    }
    
    /// 准备文本框
   private func prepareTextView() {
        //  添加
        view.addSubview(textView)
        textView.backgroundColor = UIColor.whiteColor()
        //添加布局
        textView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0)
        textView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolbar, size: nil)
        textView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: nil)
        textView.addSubview(placeHoderLabel)
        placeHoderLabel.ff_AlignInner(type: ff_AlignType.TopLeft, referView: textView, size: nil,offset: CGPoint(x: 5, y: 8))
    }
    
    //工具栏的底部约束
    var toolbarBottomCons: NSLayoutConstraint?
    
    /// 准备 toolbar
   private func prepareToolbar() {
    
        //这个具体设置的颜色，可以问平面设计师
        toolbar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
    
        view.addSubview(toolbar)
        //设置布局
        let cons = toolbar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 44))
        //记录底部约束
        toolbarBottomCons = toolbar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
    
        // 定义一个数组
        let itemSettings = [["imageName": "compose_toolbar_picture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
    
    var items = [UIBarButtonItem]()
    
    //遍历数组
    for dict in itemSettings {
//        //创建barbutton
//        //从字典中取值，如果key 不存在，会得到 nil，因此需要强行解包
//        let image = UIImage(named: dict["imageName"]!)
//        let button = UIButton()
//        button.setImage(UIImage(named: dict["imageName"]!), forState: UIControlState.Normal)
//        button.setImage(UIImage(named: dict["imageName"]! + "_highlighted"), forState: UIControlState.Highlighted)
//        button.sizeToFit()
//        
//        //设置监听方法，判断 action key 是否存在
//        if let actionName = dict["action"] {
//            button.addTarget(self, action: Selector(actionName) , forControlEvents: UIControlEvents.TouchUpInside)
//        }
//        
//        // let item = UIBarButtonItem(image: image,style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
//        let item = UIBarButtonItem(customView: button)
//        items.append(item)
        
        items.append(UIBarButtonItem(imageName: dict["imageName"]!, target: self, action: dict["action"]))
        
        //添加弹簧
        items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
    }
    
    //删除尾部多出来的一个
    items.removeLast()
        //设置 toolbar 的items
    toolbar.items = items
    
    }
    
    //准备导航栏
    private func prepareNav() {
        //左右的按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        navigationItem.rightBarButtonItem?.enabled = false
        
        //标题栏
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 35))
        
        let titleLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 15)
        titleLabel.text = "发微博"
        titleLabel.sizeToFit()
        titleView.addSubview(titleLabel)
        titleLabel.ff_AlignInner(type: ff_AlignType.TopCenter, referView: titleView, size: nil)
        
        let namelabel = UILabel(color: UIColor.lightGrayColor(), fontSize: 13)
        namelabel.text = UserAcount.sharedUserAccount?.name ?? ""
        namelabel.sizeToFit()
        titleView.addSubview(namelabel)
        namelabel.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: titleView, size: nil)
        
        
        navigationItem.titleView = titleView
    }
    //MAERK: - 懒加载控件
    //懒加载文本框
    private lazy var textView: UITextView = {
        let iv = UITextView()
        iv.text = "分享新鲜事..."
        iv.font = UIFont.systemFontOfSize(18)
        //允许上下拖动
        iv.alwaysBounceVertical = true
        //拖动关闭键盘
        iv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        return iv
    }()
    // 懒加载 toolbar
    private lazy var toolbar = UIToolbar()
    //占位标签懒加载
    private lazy var placeHoderLabel: UILabel = {
        let label = UILabel(color: UIColor.lightGrayColor(), fontSize: 18)
        label.text = "分享新鲜事..."
        label.sizeToFit()
        return label
    }()

}
